<template>
  <div class="editAccount">
    <van-nav-bar title="编辑账户" left-arrow @click-left="onClickLeft" />
    <div style="padding: 16px">
      <van-form @submit="onSubmit">
        <div style="background-color: #fff">
          <!-- <van-field
          v-model="username"
          name="类型"
          label="类型"
          placeholder="请输入类型"
          :rules="[{ required: true, message: '请输入类型' }]"
        /> -->
          <van-field
            v-model="enterpriseName"
            required
            label="企业名称"
            placeholder="请输入企业名称"
            :rules="[{ required: true, message: '请输入企业名称' }]"
          />
          <van-field
            v-model="contactName"
            required
            label="联系人"
            placeholder="请输入联系人"
            :rules="[{ required: true, message: '请输入联系人' }]"
          />
          <van-field
            v-model="contactPhone"
            required
            name="联系电话"
            label="联系电话"
            placeholder="请输入联系电话"
            :rules="[
              { required: true, message: '请输入联系电话' },
              {
                validator: (value, rule) => phoneNumberRight(value, rule),
                message: '请输入正确的手机号码',
              },
            ]"
          />
          <!-- <van-field
          v-model="username"
          name="联系邮箱"
          label="联系邮箱"
          placeholder="请输入联系邮箱"
          :rules="[{ required: true, message: '请输入联系邮箱' }]"
        /> -->
          <van-field
            readonly
            clickable
            name="area"
            required
            :value="addressData"
            label="地区选择"
            placeholder="点击选择省市区"
            @click="showArea = true"
          />
          <van-popup v-model="showArea" position="bottom">
            <van-area
              :area-list="areaList"
              @confirm="onConfirm"
              @cancel="showArea = false"
            />
          </van-popup>
          <van-field
            v-model="contactAddress"
            required
            name="联系地址"
            label="联系地址"
            placeholder="请输入联系地址"
            :rules="[{ required: true, message: '请输入联系地址' }]"
          />
          <!-- <van-field
          v-model="password"
          name="审核状态"
          label="审核状态"
          placeholder="请输入类型"
          :rules="[{ required: true, message: '请输入类型' }]"
        /> -->
          <van-field name="uploader" required label="营业执照">
            <template #input>
              <van-uploader
                :before-read="beforeRead"
                :after-read="afterRead"
                :max-count="1"
              >
                <!-- <van-button icon="plus" type="primary">点击上传</van-button> -->
              </van-uploader>
            </template>
          </van-field>
          <div style="padding: 0 16px">
            <van-image v-if="!!imgUrl" width="100%" @click="imgClick" fit="cover" :src="imgUrl">
              <template v-slot:loading>
                <van-loading type="spinner" size="20" />
              </template>
            </van-image>
          </div>
          <van-image-preview v-model="show" :images="images" @change="onChange">
          </van-image-preview>
        </div>
        <div style="margin: 16px 0">
          <van-button block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
  
<script>
import { addressObj } from "@/utils/options";
export default {
  name: "home",
  data() {
    return {
      enterpriseName: "",
      contactName: "",
      contactPhone: "",
      addressData: "",
      contactAddress: "",
      businessLicense: "",

      showArea: false,
      areaList: addressObj,

      username: "",
      password: "",
      uploader: [],
      images: [],
      show: false,
      index: 0,
      imgUrl: "",
    };
  },
  computed: {
    userInfo() {
      const userInfo = localStorage.getItem("userInfo");
      if (userInfo) {
        return JSON.parse(userInfo);
      }
      return {};
    },
    checkStatusName() {
      const userInfo = localStorage.getItem("userInfo");
      if (userInfo) {
        const checkStatus = JSON.parse(userInfo).checkStatus;
        return checkStatus === "0"
          ? "未审核"
          : checkStatus === "1"
          ? "待审核"
          : checkStatus === "2"
          ? "审核未通过"
          : checkStatus === "3"
          ? "审核通过"
          : "";
      }
      return "";
    },
    address() {
      const { userInfo } = this;
      if (userInfo) {
        return userInfo.sheng + userInfo.shi + userInfo.qu || "";
      }
      return "";
    },
  },
  methods: {
    imgClick() {
      this.show = true;
    },
    onChange(index) {
      this.index = index;
    },
    // 1.手机号码验证
    phoneNumberRight(val) {
      return /^1[3-9]\d{9}$/.test(val);
    },
    afterRead(file) {
      console.log(file.file, 'file')
      let quality = 0.5 // 压缩的质量，0~1之间，越低质量越差
      if (file.size < 3 * 1024 * 1024) {
        quality = 1
      }
      this.compressImage(file.file, quality, (blob) => {
        console.log('blob', blob)
        const formData = new FormData();
        formData.append("file", blob, '营业执照.jpg');
        // formData.append("file", file.file);
        const headers = {
          "Content-Type": "multipart/form-data",
        };
      
        this.$post("/file/upload", formData, headers).then((res) => {
          this.businessLicense = res.data;
          this.imgUrl = res.data;
          this.images = [res.data];
        });
      });
      
    },
    compressImage(file, quality, callback) {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        const img = new Image();
        img.src = e.target.result;
        img.onload = () => {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          canvas.width = img.width / 2; // 示例中简单地将宽高减半作为压缩
          canvas.height = img.height / 2;
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          canvas.toBlob((blob) => {
            callback(blob);
          }, 'image/jpeg', quality);
        };
      };
    },
    beforeRead(file) {
      if (
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/jpg"
      ) {
        this.$toast("请上传图片");
        return false;
      }
      const maxSize = 10 * 1024 * 1024
      if (file.size > maxSize) {
        this.$toast({
          message: "请上传一张小于10M的图片",
          duration: 1000,
        });
        return false;
      }
      return true;
    },
    onConfirm(values) {
      this.addressData = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join("/");
      this.showArea = false;
    },
    onClickLeft() {
      this.$router.push("/account");
    },
    onSubmit() {
      const {
        enterpriseName,
        contactName,
        contactPhone,
        addressData,
        contactAddress,
        businessLicense,
      } = this;
      const addressList = addressData.split("/");
      const params = {
        enterpriseName,
        contactName,
        contactPhone,
        sheng: addressList[0],
        shi: addressList[1],
        qu: addressList[2],
        contactAddress,
        businessLicense,
        customerId: this.userInfo.customerId,
      };
      this.$post("/customer/updateInfo", params).then((res) => {
        this.getNewToken();
      });
    },
    getNewToken() {
      this.$post("/customer/exchangeToken").then((res) => {
        if (res && res.code * 1 === 200) {
          localStorage.setItem("token", res.data);
          this.onClickLeft();
        }
      });
    },
    
  },
  mounted() {
    const { userInfo } = this;
    if (JSON.stringify(userInfo) !== "{}") {
      this.enterpriseName = userInfo.enterpriseName;
      this.contactName = userInfo.contactName;
      this.contactPhone = userInfo.contactPhone;
      this.contactAddress = userInfo.contactAddress;
      this.addressData =
       userInfo.sheng ? userInfo.sheng + "/" + userInfo.shi + "/" + userInfo.qu : '';
      this.businessLicense = userInfo.businessLicense;
      this.images = [userInfo.businessLicense];
      this.imgUrl = userInfo.businessLicense;
    }
  },
};
</script>
<style scoped>
.editAccount {
  background-color: #f5f5f5;
  height: 100%;
  width: 100%;
}
</style>
